package com.cskaoyan.market.service;

import com.cskaoyan.market.bo.OrderCommentBo;
import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.MarketCommentMapper;
import com.cskaoyan.market.db.mapper.MarketOrderGoodsMapper;
import com.cskaoyan.market.db.mapper.MarketOrderMapper;
import com.cskaoyan.market.domain.HandleOption;
import com.cskaoyan.market.domain.OrderStatus;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.OrderGoodsVo;
import com.cskaoyan.market.vo.OrderInfoVo;
import com.cskaoyan.market.vo.OrderListVo;
import com.github.pagehelper.PageHelper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author: 鲸落
 * @Date: 2024/05/20/16:47
 * @Version: 1.0
 * @Description:
 */
@Service
@Data
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketCommentMapper commentMapper;

    @Override
    public Object list(Integer showType, Integer page, Integer limit, MarketUser user) {
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId()).andLogicalDeleted(true);
        // showType要展示的类型：0--全部 1--待付款  2--待发货  3--待收货  4--待评价
        // 根据要展示的订单状态对订单进行处理，添加查询条件
        switch (showType) {
            case 0:
                break;
            case 1:
                criteria.andOrderStatusEqualTo((short) 101);
                break;
            case 2:
                criteria.andOrderStatusEqualTo((short) 201);
                break;
            case 3:
                criteria.andOrderStatusEqualTo((short) 301);
                break;
            case 4:
                criteria.andOrderStatusIn(Arrays.asList((short) 401.402));
                break;
        }
        // 开启分页查询
        PageHelper.startPage(page, limit);
        // 查找当前类型、当前用户所有的订单
        List<MarketOrder> orderList = orderMapper.selectByExample(orderExample);
        // orderGoods表所有的商品
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.createCriteria().andLogicalDeleted(true);
        List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        Map<Integer, List<OrderGoodsVo>> orderGoodsVoMap = orderGoodsListByOrderId(orderGoodsList);
        // 响应体中的list
        List<OrderListVo> orderListVoList = new ArrayList<>();
        for (MarketOrder order : orderList) {
            // 根据订单id查找对应的订单商品信息
            List<OrderGoodsVo> orderGoodsVoList = orderGoodsVoMap.get(order.getId());

            // 根据当前订单的信息设置要显示的功能按钮
            Map<String, Boolean> handleOption = getHandleOption(order);
            // 要填充的Vo数据
            OrderListVo orderListVo = new OrderListVo(order.getId(), false, order.getOrderSn(),
                    new OrderStatus().getOrderStatusMap().get(order.getOrderStatus()), handleOption,
                    order.getAftersaleStatus(),order.getActualPrice(), orderGoodsVoList);
            orderListVoList.add(orderListVo);
        }
        return ResponseUtil.okList(orderListVoList, orderList);
    }

    @Override
    public Map<String, Object> detail(Integer orderId) {
        // 要返回的结果
        Map<String,Object> data = new HashMap<>();
        data.put("expressInfo",new ArrayList<>());
        // 订单商品信息
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        data.put("orderGoods",orderGoods);
        // 订单信息
        MarketOrder order = orderMapper.selectByPrimaryKeyWithLogicalDelete(orderId,false);
        // 根据当前订单的信息设置要显示的功能按钮
        Map<String, Boolean> handleOption = getHandleOption(order);
        // 要填充的orderInfoVo
        OrderInfoVo orderInfoVo = new OrderInfoVo(order.getConsignee(),order.getAddress(),order.getAddTime(),
                order.getOrderSn(),order.getActualPrice(),order.getMobile(),order.getMessage(),
                new OrderStatus().getOrderStatusMap().get(order.getOrderStatus()), order.getAftersaleStatus(),
                order.getGoodsPrice(),order.getCouponPrice(),order.getId(), order.getFreightPrice(),handleOption);
        data.put("orderInfo",orderInfoVo);
        return data;
    }

    @Override
    public void delete(Integer orderId) {
        // 删除订单表中的订单  逻辑删除
        orderMapper.logicalDeleteByPrimaryKey(orderId);
        // 删除订单商品表中的商品  逻辑删除
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        orderGoodsMapper.logicalDeleteByExample(orderGoodsExample);
    }

    @Override
    public void refund(Integer orderId) {
        MarketOrder updateOrder = new MarketOrder();
        updateOrder.setId(orderId);
        updateOrder.setOrderStatus((short)202);
        updateOrder.setComments((short) 0);
        updateOrder.setAftersaleStatus((short) 0);
        updateOrder.setUpdateTime(LocalDateTime.now());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    @Override
    public void confirm(Integer orderId) {
        MarketOrder updateOrder = new MarketOrder();
        updateOrder.setId(orderId);
        updateOrder.setOrderStatus((short)401);
        updateOrder.setAftersaleStatus((short) 0);
        updateOrder.setConfirmTime(LocalDateTime.now());
        // 查询当前订单有几个商品
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> orderGoods = orderGoodsMapper.selectByExampleSelective(orderGoodsExample, MarketOrderGoods.Column.orderId);
        updateOrder.setComments((short) orderGoods.size());
        updateOrder.setUpdateTime(LocalDateTime.now());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        return orderGoodsMapper.selectOneByExample(orderGoodsExample);
    }

    @Override
    public void cancel(Integer orderId) {
        MarketOrder updateOrder = new MarketOrder();
        updateOrder.setId(orderId);
        updateOrder.setOrderStatus((short)102);
        updateOrder.setAftersaleStatus((short) -1);
        updateOrder.setConfirmTime(LocalDateTime.now());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    @Override
    public void comment(OrderCommentBo orderCommentBo,Integer userId) {
        // 先根据orderGoodsId找到要评论的商品
        MarketComment comment = new MarketComment();
        MarketOrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(orderCommentBo.getOrderGoodsId());
        comment.setValueId(orderGoods.getGoodsId());
        comment.setType((byte) 0);
        comment.setContent(orderCommentBo.getContent());
        comment.setUserId(userId);
        comment.setHasPicture(orderCommentBo.getHasPicture());
        comment.setPicUrls(orderCommentBo.getPicUrls());
        comment.setStar(orderCommentBo.getStar());
        comment.setAddTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        comment.setDeleted(false);
        // 插入comment表
        commentMapper.insert(comment);
        // 更新order表中待评论的商品数量
        MarketOrder updateOrder = new MarketOrder();
        Integer orderId = orderGoods.getOrderId();
        updateOrder.setId(orderId);
        Short comments = orderMapper.selectByPrimaryKey(orderId).getComments(); // 原来待评伦的商品数量
        updateOrder.setComments((short) (comments-1));
        updateOrder.setUpdateTime(LocalDateTime.now());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
        // 还要更新orderGoods表中的comment
        orderGoods.setComment(comment.getId());
        orderGoods.setUpdateTime(LocalDateTime.now());
        orderGoodsMapper.updateByPrimaryKeySelective(orderGoods);
    }

    // 根据订单id对订单商品进行分类
    public Map<Integer, List<OrderGoodsVo>> orderGoodsListByOrderId(List<MarketOrderGoods> orderGoodsList) {
        Map<Integer, List<OrderGoodsVo>> orderGoodsVoMap = new HashMap<>();
        for (MarketOrderGoods good : orderGoodsList) {
            // 当前商品的订单id
            Integer orderId = good.getOrderId();
            // 先get后set
            List<OrderGoodsVo> orderGoodsVoList = orderGoodsVoMap.get(orderId);
            if (orderGoodsVoList == null) {
                orderGoodsVoList = new ArrayList<>();
            }
            // 填充Vo数据
            OrderGoodsVo orderGoodsVo = new OrderGoodsVo(good.getId(), good.getNumber(), good.getGoodsName(),
                    good.getPicUrl(), good.getPrice(), good.getSpecifications());
            orderGoodsVoList.add(orderGoodsVo);
            orderGoodsVoMap.put(orderId, orderGoodsVoList);
        }
        return orderGoodsVoMap;
    }

    // 根据当前订单的状态码来判断要显示哪个功能按钮
    public Map<String, Boolean> getHandleOption(MarketOrder order) {
        // 当前订单的状态码
        Short orderStatus = order.getOrderStatus();
        // 返回的结果
        Map<String, Boolean> handleOption = new HandleOption().getHandleOption();
        switch (orderStatus) {
            case 101:
                handleOption.put("pay", true);
                handleOption.put("cancel", true);
                break;
            case 102:
            case 103:
                handleOption.put("delete", true);
                handleOption.put("rebuy", true);
                break;
            case 201:
                handleOption.put("refund", true);
                break;
            case 202:
                break;
            case 203:
                handleOption.put("delete", true);
                break;
            case 301:
                handleOption.put("confirm", true);
                handleOption.put("aftersale", true);
                break;
            case 401:
            case 402:
                handleOption.put("delete", true);
                handleOption.put("aftersale", true);
                handleOption.put("rebuy", true);
                if(order.getComments() > 0){
                    handleOption.put("comment", true);
                }
                break;
        }
        return handleOption;
    }
}
